package org.xyf.workflow.utils;

import jakarta.servlet.http.Part;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;

import java.io.*;


public class FileUtils {


    public static void fileUpload(Part filePart, String storagePath) throws IOException {
        final String fileName = getFileName(filePart);
        if (!StringUtils.hasLength(fileName)) {
            throw new RuntimeException("文件名不能为空!");
        }
        File storageDir = new File(storagePath);
        File file = new File(storageDir, fileName);
        if (!storageDir.exists()) {
            throw new RuntimeException("请确认此文件路径:" + storagePath + " 是否存在!");
        }
        if(!storageDir.canWrite()){
            throw new RuntimeException("当前目录:"+storagePath+" 不可写入!");
        }
        try (InputStream fileContent = filePart.getInputStream();
             OutputStream out = new FileOutputStream(file)) {
            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = fileContent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
        }
    }


    public static String getFileName(final Part part) {

        final String partHeader = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
        for (String content : partHeader.split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

}
